package view;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Account;
import model.Author;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/Login")
public class LoginServlet extends Servlet {

	private static final long serialVersionUID = -7963401355529771881L;

	private Account login(String username, String password) throws Exception {
		Account account = new Account(username, password);
		if (account.login()) {
			return account;
		} else {
			throw new Exception("Username ou senha inválidos!");
		}
	}

	@Override
	void fillGetContent(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
		if (request.getSession().getAttribute("author") != null) {
			try {
				response.sendRedirect("Controller?button=Pesquisar");
			} catch (IOException e) {
				out.println(HtmlFactory.createErrorMessage(e.getMessage()));
			}
			out.println(HtmlFactory.createSuccessMessage("Você já está logado(a)!"));
		} else {
			printLoginPage(out, "");
		}
	}

	@Override
	void fillPostContent(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");

		try {
			if (login(username, password) != null) {
				HttpSession session = request.getSession();
				Author author = new Author(username, password);
				session.setAttribute("author", author);

				response.sendRedirect("Controller?button=Pesquisar");
				out.println(HtmlFactory.createSuccessMessage("Seja bem-vindo(a)," + author.getFirstName() + "!"));
			}
		} catch (Exception ex) {
			out.println(HtmlFactory.createErrorMessage(ex.getMessage()));
			printLoginPage(out, username);
		}
	}

	private void printLoginPage(PrintWriter out, String username) {
		// FIXME só pra acelerar
		// username = "userfabio";
		// String pass = "passfabio";

		/* @formatter:off */
		String loginForm = ""
		+ "	<div id='loginContainer'>"
		+ "		<form action='Controller' method='POST' style='display:inline;'>"
		+ "			<label for='username'>Username:</label>"
		+ "			<input id='username' type='text' name='username' value='"+username+"'></br>"
		+ "			<label for='password'>Password: </label>"
		+ "			<input id='password' type='password' name='password'></br>"
		+ "			<input type='submit' name='button' value='Login'>"
		+ "		</form>"
		+ "		<form action='Controller' method='GET' style='display:inline;'>"
		+ "			<input type='submit' name='button' value='Registrar'>"
		+ "		</form>"
		+ "	</div>";
		/* @formatter:on */

		out.println(loginForm);
	}
}
